package com.nlscan.nhub.test.ui

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.textfield.TextInputEditText
import com.nlscan.nhub.test.R
import com.nlscan.nhub.test.common.AppConst
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.regex.Pattern

class SendCmdBroadcastActivity : AppCompatActivity() {
    // View 引用
    private lateinit var etMacAddresses: TextInputEditText
    private lateinit var btnSendBroadcast: Button
    private lateinit var tvDebugInfo: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_send_cmd_broadcast)

        initViews()
        setupListeners()
    }

    private fun initViews() {
        etMacAddresses = findViewById(R.id.etMacAddresses)
        btnSendBroadcast = findViewById(R.id.btnSendBroadcast)
        tvDebugInfo = findViewById(R.id.tvDebugInfo)
    }

    private fun setupListeners() {
        btnSendBroadcast.setOnClickListener {
            val input = etMacAddresses.text?.toString()?.trim()
            handleSendBroadcast(input)
        }

        // 输入框快捷操作
        etMacAddresses.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                btnSendBroadcast.performClick()
                true
            } else {
                false
            }
        }
    }

    private fun handleSendBroadcast(input: String?) {
        var debugInfo = buildString {
            appendln("=== 广播发送请求 ===")
            appendln("时间: ${SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())}")
        }

        // 构建广播 Intent
        val intent = Intent(AppConst.ACTION_SEND_NLS_CMD).apply {
            putExtra(AppConst.EXTRA_DEVICE_ADDRESS, input)
            putExtra(AppConst.EXTRA_NLS_CMD, "#BEEPON2000F300T20V")
        }

        when {
            input.isNullOrEmpty() -> {
                debugInfo += "目标设备：所有已连接设备\n"
                sendBroadcast(intent)
                showDebugInfo(debugInfo + "状态：全局广播已发送")
            }

            else -> {
                val addresses = input.split(";").map { it.trim() }
                debugInfo += """
                    |目标设备：${addresses.joinToString()}
                    |有效地址：${addresses.filter { isValidMac(it) }.joinToString()}
                    |""".trimMargin()

                sendBroadcast(intent)
                showDebugInfo(debugInfo + "状态：定向广播已发送")
            }
        }
    }

    private fun isValidMac(address: String): Boolean {
        return Pattern.matches("^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$", address)
    }

    private fun showDebugInfo(info: String) {
        tvDebugInfo.text = info
        Log.d("BroadcastDebug", info.replace("\n", " | "))
    }
}
